package com.qiguliuxing.dts.db.service;

import com.github.pagehelper.PageHelper;
import com.qiguliuxing.dts.db.bean.CommentInfo;
import com.qiguliuxing.dts.db.bean.Commenter;
import com.qiguliuxing.dts.db.dao.DtsCommentMapper;
import com.qiguliuxing.dts.db.dao.ex.CommentMapperEx;
import com.qiguliuxing.dts.db.domain.DtsAdmin;
import com.qiguliuxing.dts.db.domain.DtsComment;
import com.qiguliuxing.dts.db.domain.DtsCommentExample;

import com.qiguliuxing.dts.db.domain.DtsUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DtsCommentService {
	@Resource
	private DtsCommentMapper commentMapper;
	
	@Resource
	private CommentMapperEx commentMapperEx;

	@Autowired
	private DtsUserService userService;

	@Autowired
	private DtsAdminService adminService;

	public List<DtsComment> queryGoodsByGid(Integer id, int offset, int limit) {
		DtsCommentExample example = new DtsCommentExample();
		example.setOrderByClause(DtsComment.Column.addTime.desc());
		example.or().andValueIdEqualTo(id).andTypeEqualTo((byte) 0).andIsRootEqualTo(true).andDeletedEqualTo(false);
		PageHelper.startPage(offset, limit);
		return commentMapper.selectByExample(example);
	}

	public List<DtsComment> query(Byte type, Integer valueId, Integer showType, Integer offset, Integer limit) {
		DtsCommentExample example = new DtsCommentExample();
		example.setOrderByClause(DtsComment.Column.addTime.desc());
		if (showType == 0) {
			example.or().andValueIdEqualTo(valueId).andTypeEqualTo(type).andDeletedEqualTo(false).andIsRootEqualTo(true);
		} else if (showType == 1) {
			example.or().andValueIdEqualTo(valueId).andTypeEqualTo(type).andHasPictureEqualTo(true)
					.andDeletedEqualTo(false).andIsRootEqualTo(true);
		} else {
			throw new RuntimeException("showType不支持");
		}
		PageHelper.startPage(offset, limit);
		return commentMapper.selectByExample(example);
	}

	/**
	 * 获取评论数，只能为根评论
	 * @param type
	 * @param valueId
	 * @param showType
	 * @return
	 */
	public int count(Byte type, Integer valueId, Integer showType) {
		DtsCommentExample example = new DtsCommentExample();
		if (showType == 0) {
			example.or().andValueIdEqualTo(valueId).andTypeEqualTo(type).andIsRootEqualTo(true).andDeletedEqualTo(false);
		} else if (showType == 1) {
			example.or().andValueIdEqualTo(valueId).andTypeEqualTo(type).andIsRootEqualTo(true).andHasPictureEqualTo(true)
					.andDeletedEqualTo(false);
		} else {
			throw new RuntimeException("showType不支持");
		}
		return (int) commentMapper.countByExample(example);
	}

	public int save(DtsComment comment) {
		comment.setAddTime(LocalDateTime.now());
		comment.setUpdateTime(LocalDateTime.now());
		return commentMapper.insertSelective(comment);
	}

	/*public List<DtsComment> querySelective(String userId, String valueId, Integer page, Integer size, String sort,
			String order) {
		DtsCommentExample example = new DtsCommentExample();
		DtsCommentExample.Criteria criteria = example.createCriteria();

		// type=2 是订单商品回复，这里暂只查询商品根评论
		criteria.andTypeNotEqualTo((byte) 2);
		criteria.andIsRootEqualTo(true);

		if (!StringUtils.isEmpty(userId)) {
			criteria.andUserIdEqualTo(Integer.valueOf(userId));
		}
		if (!StringUtils.isEmpty(valueId)) {
			criteria.andValueIdEqualTo(Integer.valueOf(valueId)).andTypeEqualTo((byte) 0);
		}
		criteria.andDeletedEqualTo(false);

		//评论进行排序,按评论时间倒序排列
		if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
			example.setOrderByClause(sort + " " + order);
		}
		//example.setOrderByClause("value_id asc, root_id asc, add_time asc");

		PageHelper.startPage(page, size);
		return commentMapper.selectByExample(example);
	}*/

	public void deleteById(Integer id) {
		commentMapper.logicalDeleteByPrimaryKey(id);
	}

	public List<Map<String, Object>> queryReply(Integer id, Integer valueId) {
		DtsCommentExample example = new DtsCommentExample();
		example.setOrderByClause(DtsComment.Column.addTime.asc());//根据评论时间排序
		example.or().andValueIdEqualTo(valueId).andIsRootEqualTo(false).andRootIdEqualTo(id).andIdNotEqualTo(id).andDeletedEqualTo(false);
		List<DtsComment> commentList = commentMapper.selectByExample(example);
		List<Map<String, Object>> commentVoList = new ArrayList<>(commentList.size());

		//设置评论者与回复人
		for (DtsComment comment : commentList) {
			Map<String, Object> commentVo = new HashMap<>();
			commentVo.put("addTime", comment.getAddTime());
			commentVo.put("content", comment.getContent());
			commentVo.put("picList", comment.getPicUrls());

			//本条评论的评论人
			Commenter commenter = getCommenter(comment);
			commentVo.put("commenter", commenter);

			//本条评论的回复人
			DtsComment repliedComment = commentMapper.selectByPrimaryKey(comment.getRepliedToId());
			Commenter replier = getCommenter(repliedComment);
			commentVo.put("replier", replier);

			commentVoList.add(commentVo);
		}

		return commentVoList;
	}

	/**
	 * 根据评论记录获取本评论的评论者信息
	 * @param comment
	 * @return
	 */
	private Commenter getCommenter(DtsComment comment) {
		if(comment == null){
			return null;
		}
		Commenter commenter = null;
		if (comment.getUserId() != null){
			DtsUser user = userService.findById(comment.getUserId());
			if(user != null){
				commenter = new Commenter(user.getNickname(), user.getAvatar(),"user", user.getId());
			}
		}
		if(commenter == null && comment.getAdminId() != null){
			DtsAdmin admin = adminService.findAdmin(comment.getAdminId());
			if (admin != null) {
				commenter = new Commenter(admin.getUsername(), admin.getAvatar(),"admin", admin.getId());
			}
		}
		commenter.setComentId(comment.getId());
		return commenter;
	}

	public DtsComment findById(Integer id) {
		return commentMapper.selectByPrimaryKey(id);
	}

	/**
	 * 入驻店铺对应商品的评价
	 * @param brandIds
	 * @param nickname
	 * @param goodsSn
	 * @param page
	 * @param size
	 * @param sort
	 * @param order
	 * @return
	 */
	public List<CommentInfo> queryBrandCommentSelective(List<Integer> brandIds, String nickname, String goodsSn,
			Integer page, Integer size, String sort, String order) {

		// 评论进行排序 按评论时间倒序
		String orderBySql = null;
		if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
			orderBySql = "o."+sort + " " + order;
		}
		// orderBySql = "o.value_id asc, o.root_id asc, o.add_time asc";
		
		String brandIdsSql = null;
		if (brandIds != null) {
			brandIdsSql = "";
			for (Integer brandId : brandIds) {
				brandIdsSql += "," + brandId;
			}
			brandIdsSql = " and g.brand_id in (" + brandIdsSql.substring(1) + ") ";
		}
		PageHelper.startPage(page, size);
		
		Byte type = (byte) 0; // 品牌入驻管理员限定只查商品评论
		List<CommentInfo> commentInfos = commentMapperEx.queryBrandComment(type, nickname, goodsSn, orderBySql, brandIdsSql);

		// 获取回复并设置回复信息
        for (CommentInfo commentInfo : commentInfos) {
			List<Commenter> repliers = queryAdminReply(commentInfo.getId(), commentInfo.getValueId());
			commentInfo.setRepliers(repliers);
			commentInfo.setReplyNum(repliers == null ? 0 : repliers.size());
		}
		return commentInfos;
	}

	public List<Commenter> queryAdminReply(Integer id,Integer valueId) {
		List<Commenter> repliers = null;
		List<Map<String, Object>> replyMapList =  queryReply(id, valueId);
		if (replyMapList != null && replyMapList.size() > 0) {
			repliers = new ArrayList<Commenter>(replyMapList.size());
		}
		for (Map<String, Object> replyMap : replyMapList) {
			Commenter reply = (Commenter) replyMap.get("commenter");
			reply.setAddTime((LocalDateTime) replyMap.get("addTime"));
			reply.setPicList((String[]) replyMap.get("picList"));
			reply.setCommentContent((String) replyMap.get("content"));
			repliers.add(reply);
		}
		return repliers;
	}

	public void update(DtsComment comment) {
		commentMapper.updateByPrimaryKeySelective(comment);
	}

	/**
	 * 回复评论
	 */
	public void reply(Integer adminId,Integer commentId,String content,DtsComment oldComment) {

		// 创建评价回复
		DtsComment comment = new DtsComment();
		comment.setType(oldComment.getType());
		comment.setValueId(oldComment.getValueId());
		comment.setContent(content);
		comment.setUserId(null);
		comment.setHasPicture(false); // 评价回复没有用
		comment.setPicUrls(new String[] {}); // 评价回复没有用
		comment.setStar((short) 0); // 评价回复没有用
		comment.setAddTime(LocalDateTime.now());//创建时间
		comment.setUpdateTime(LocalDateTime.now());//更新时间
		comment.setRepliedToId(commentId);//回复的评论
		comment.setIsRoot(false);//非根评论
		comment.setRootId(oldComment.getRootId() != null && oldComment.getRootId().intValue() > 0 ? oldComment.getRootId() : oldComment.getId());
		comment.setAdminId(adminId);
		save(comment);
	}

}
